export default defineNuxtPlugin((nuxtApp) => {
    if (import.meta.client) {
        const lang = localStorage.getItem("lang")
            ? localStorage.getItem("lang")
            : "zh_tw";
        localStorage.setItem("lang", lang);
        document.cookie = `i18n_redirected=${lang};`;
        const dataLang = lang === "en" ? lang : "";
        nuxtApp.$i18n.setLocale(lang);
    }
    if (import.meta.server) {
        // 服务端读取请求头获取cookie设置语言
        const cookies = useRequestHeaders(["cookie"]).cookie || "";
        const match = cookies.match(/i18n_redirected=([^;]+)/);
        const preferredLanguage = match ? match[1] : "zh_tw";
        const dataLang = preferredLanguage === "en" ? preferredLanguage : "";
        nuxtApp.$i18n.setLocale(preferredLanguage);
        useHead({
            htmlAttrs: {
                "data-lang": dataLang,
            },
        });
    }
});
